<template>
  <div class="echart-bar-wrapper" :style="containerStyle">
    <v-chart ref="chartRef" :option="chartOption" :style="chartStyle" autoresize />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';
import { shouldUpdateChartData } from '@/utils/shallow-equal';

// 注册ECharts组件
use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent
]);

// Props定义
interface Props {
  title?: string;
  backgroundColor?: string;
  xAxisData?: string[];
  seriesData?: number[];
  barColor?: string;
  barWidth?: string;
  showDataZoom?: boolean;
  isHorizontal?: boolean;
  dataBinding?: IDataBindingConfig;
}

const props = withDefaults(defineProps<Props>(), {
  title: '柱状图',
  backgroundColor: 'transparent',
  xAxisData: () => ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
  seriesData: () => [120, 200, 150, 80, 70, 110, 130],
  barColor: '#409EFF',
  barWidth: '60%',
  showDataZoom: false,
  isHorizontal: false
});

const chartRef = ref();

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  title: props.title,
  backgroundColor: props.backgroundColor,
  xAxisData: [...props.xAxisData],
  seriesData: [...props.seriesData],
  barColor: props.barColor,
  barWidth: props.barWidth,
  showDataZoom: props.showDataZoom,
  isHorizontal: props.isHorizontal
});

// 使用数据绑定（hide属性由render-core处理，组件跳过）
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';

const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 数据更新已由数据绑定composable处理，这里只需要直接更新属性

// 监听props变化，同步到响应式属性对象
watch(
  () => props.xAxisData,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'xAxisData') {
        componentProps.value.xAxisData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

watch(
  () => props.seriesData,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!shouldUseDataBinding || props.dataBinding?.targetProperty !== 'seriesData') {
        componentProps.value.seriesData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

// 容器样式
const containerStyle = computed(() => ({
  width: '100%',
  height: '100%',
  backgroundColor: componentProps.value.backgroundColor
}));

// 图表样式
const chartStyle = computed(() => ({
  width: '100%',
  height: '100%'
}));

// ECharts配置
const chartOption = computed(() => {
  const baseConfig = {
    title: {
      text: componentProps.value.title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      bottom: 10,
      data: ['数据']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: props.showDataZoom ? '15%' : '10%',
      containLabel: true
    },
    dataZoom: props.showDataZoom
      ? [
          {
            type: 'inside',
            start: 0,
            end: 100
          },
          {
            start: 0,
            end: 100,
            height: 30
          }
        ]
      : undefined,
    series: [
      {
        name: '数据',
        type: 'bar',
        barWidth: props.barWidth,
        itemStyle: {
          color: componentProps.value.barColor
        },
        data: componentProps.value.seriesData
      }
    ]
  };

  if (props.isHorizontal) {
    // 水平柱状图（条形图）
    return {
      ...baseConfig,
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data:
          componentProps.value.xAxisData.length > 0
            ? componentProps.value.xAxisData
            : componentProps.value.seriesData.map((_, index) => `项目${index + 1}`)
      }
    };
  } else {
    // 垂直柱状图
    return {
      ...baseConfig,
      xAxis: {
        type: 'category',
        data:
          componentProps.value.xAxisData.length > 0
            ? componentProps.value.xAxisData
            : componentProps.value.seriesData.map((_, index) => `项目${index + 1}`)
      },
      yAxis: {
        type: 'value'
      }
    };
  }
});

// 监听props变化，同步到响应式属性对象
watch(
  () => props.title,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'title') {
        componentProps.value.title = newValue;
      }
    }
  }
);

watch(
  () => props.xAxisData,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'xAxisData') {
        componentProps.value.xAxisData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

watch(
  () => props.seriesData,
  (newValue, oldValue) => {
    // 使用浅比较优化，避免不必要的更新
    if (shouldUpdateChartData(newValue, oldValue)) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'seriesData') {
        componentProps.value.seriesData = [...newValue];
      }
    }
  },
  { deep: false } // 关闭深度监听，依赖浅比较
);

watch(
  () => props.barColor,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'barColor') {
        componentProps.value.barColor = newValue;
      }
    }
  }
);

watch(
  () => props.backgroundColor,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      if (!props.dataBinding?.enabled || props.dataBinding.targetProperty !== 'backgroundColor') {
        componentProps.value.backgroundColor = newValue;
      }
    }
  }
);

// 提供图表实例方法
const getChartInstance = () => {
  return chartRef.value?.getEchartsInstance();
};

defineExpose({
  getChartInstance,
  componentProps
});
</script>

<style scoped>
.echart-bar-wrapper {
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}
</style>
